 package com.glory.dgcpcpda.activity.mfg;

import android.os.Build;
import android.os.Handler;
import android.util.SparseArray;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.RequiresApi;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.fastjson.JSONObject;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.glory.dgcpcpda.R;
import com.glory.dgcpcpda.adapter.AddCarrierDataAdapter;
import com.glory.dgcpcpda.adapter.CarrierCheckAdapter;
import com.glory.dgcpcpda.adapter.PackageCheckAdapter;
import com.glory.dgcpcpda.adapter.RunLotListAdapter;
import com.glory.dgcpcpda.base.BaseActivity;
import com.glory.dgcpcpda.base.Constant;
import com.glory.dgcpcpda.callback.CustomDialogEntityCallBack;
import com.glory.dgcpcpda.entity.EqpInfoEntity;
import com.glory.dgcpcpda.entity.LotInfoEntity;
import com.glory.dgcpcpda.entity.response.BaseResponseBean;
import com.glory.dgcpcpda.utils.LotUtils;
import com.glory.dgcpcpda.utils.NetUtils;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.reflect.TypeToken;
import com.lzy.okgo.model.Response;
import com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_CommonCallback;
import com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_DialogEntityCallBack;
import com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_EntityCallBack;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_DialogUtils;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_LogUtils;
import com.pda.platform.ui.ui_pdaplatform.view.FreeUI_ClearEditText;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * FileName: FTWorkBeginActivity
 * Author: XJH
 * Date: 2020/5/21 16:23
 * Description:FT测试开始作业
 * History:
 */
public class FTWorkBeginActivity extends BaseActivity {


    @BindView(R.id.tvTitle)
    TextView tvTitle;
    @BindView(R.id.tvBaseSubmit)
    TextView tvBaseSubmit;
    @BindView(R.id.tvLotState)
    TextView tvLotState;
    @BindView(R.id.tvLotStep)
    TextView tvLotStep;
    @BindView(R.id.tvLotHoldState)
    TextView tvLotHoldState;
    @BindView(R.id.etLot)
    FreeUI_ClearEditText etLot;
    @BindView(R.id.etEqpWorkID)
    FreeUI_ClearEditText etEqpWorkID;
    @BindView(R.id.tvCircuit)
    TextView tvCircuit;
    @BindView(R.id.tvNumber)
    TextView tvNumber;
    @BindView(R.id.etEqpItemWorkID)
    FreeUI_ClearEditText etEqpItemWorkID;
    @BindView(R.id.rvTestEqpWorkList)
    RecyclerView rvTestEqpWorkList;
    @BindView(R.id.etCarrier)
    FreeUI_ClearEditText etCarrier;
    @BindView(R.id.rvCarrierList)
    RecyclerView rvCarrierList;
    @BindView(R.id.etMaterielID)
    FreeUI_ClearEditText etMaterielID;
    @BindView(R.id.rvMaterielList)
    RecyclerView rvMaterielList;
    @BindView(R.id.llMain)
    LinearLayout llMain;
    @BindView(R.id.rvRunLotList)
    RecyclerView rvRunLotList;
    @BindView(R.id.rvPcsQtyList)
    RecyclerView rvPcsQtyList;
    @BindView(R.id.tvAdd)
    TextView tvAdd;
    @BindView(R.id.etPcs)
    FreeUI_ClearEditText etPcs;
    @BindView(R.id.etQty)
    FreeUI_ClearEditText etQty;
    @BindView(R.id.etProjectPcs)
    LinearLayout etProjectPcs;
    @BindView(R.id.etProjectQty)
    LinearLayout etProjectQty;
    private CarrierCheckAdapter mCarrierAdapter;
    private List<String> mDurablelist;
    private AddCarrierDataAdapter mCarrierAdapter2;
    private AddCarrierDataAdapter mPcsQtyAdapter;
    private String mLineID = "";
    private RunLotListAdapter mRunAdapter;
    private LotInfoEntity lotInfoEntity;
    private PackageCheckAdapter mPackageCheckAdapter;
    private List<String> isScanmDurablelist;
    private boolean isCheck = false;

    @Override
    protected int getLayoutResId() {
        return R.layout.activity_work_begin_ft;
    }

    @Override
    protected void initView() {
        tvTitle.setText("开始作业");
        setMainLayout(llMain);
        showTips();
        initRecyclerView(rvCarrierList, this);
        initRecyclerView(rvTestEqpWorkList,this);
        initRecyclerView(rvRunLotList,this);
        initRecyclerView(rvMaterielList, this);
        initRecyclerView(rvPcsQtyList, this);
        mPackageCheckAdapter = new PackageCheckAdapter(null);
        rvMaterielList.setAdapter(mPackageCheckAdapter);
        mCarrierAdapter = new CarrierCheckAdapter(null);
        mCarrierAdapter2 = getCarrierAdapter();
        rvTestEqpWorkList.setAdapter(mCarrierAdapter2);
        rvCarrierList.setAdapter(this.mCarrierAdapter);
        mRunAdapter = new RunLotListAdapter(null);
        mRunAdapter.openLoadAnimation(BaseQuickAdapter.ALPHAIN);
        mRunAdapter.isFirstOnly(true);
        rvRunLotList.setAdapter(mRunAdapter);
        mPcsQtyAdapter = getCarrierAdapter();
        rvPcsQtyList.setAdapter(mPcsQtyAdapter);
        isCheck=false;

        etMaterielID.setShowSoftInputOnFocus(false);
        //隐藏键盘
        InputMethodManager imm = (InputMethodManager) getSystemService(getApplicationContext().INPUT_METHOD_SERVICE);
        //隐藏
        imm.hideSoftInputFromWindow(etMaterielID.getWindowToken(), 0);
        etMaterielID.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                // 获取软键盘的显示状态
                boolean isOpen=imm.isActive();
                //判断是否失去焦点
                if(!hasFocus){
                    //判断是否打开软键盘
                    if (isOpen){
                        imm.toggleSoftInput(0,InputMethodManager.HIDE_NOT_ALWAYS);
                    }
                }
            }
        });

        initEdit(etCarrier, a -> {
            String zjmsg = etCarrier.getText().toString();

            etCarrier.setText("");
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    etCarrier.requestFocus();
                }
            },500);


            if (mDurablelist == null) {
                showToast("请先扫描批次号!", false);
                return;
            }

            FreeApi_LogUtils.saveErrorMessages(zjmsg,"扫描的载具：");
            for (int i = 0; i < mDurablelist.size(); i++) {
                if (mDurablelist.get(i).equalsIgnoreCase(zjmsg)){
                    if(!isScanmDurablelist.contains(mDurablelist.get(i))){
                        isScanmDurablelist.add(mDurablelist.get(i));
                        break;
                    }
                }
            }

            mCarrierAdapter.setNewData(mDurablelist);

            for (int i = 0; i < mDurablelist.size(); i++) {
                if (isScanmDurablelist.contains(mDurablelist.get(i))){
                    this.mCarrierAdapter.setCheck(mDurablelist.get(i));
                }
            }
        });

        initEdit(etEqpItemWorkID, s -> {
            if (getText(etEqpWorkID).equals("")){
                showToast("分选机不能为空",false);
                return;
            }

            if (mCarrierAdapter2.getData().contains(s)) {
                showToast("当前测试机已添加到测试机列表中", false);
                return;
            }

            //请求设备类型、测试机列表
            LotUtils.searchEqpInfo(getText(etEqpWorkID), FTWorkBeginActivity.this, getSupportFragmentManager(), new LotUtils.netCallback<EqpInfoEntity>() {
                @Override
                public void onSuccess(EqpInfoEntity response) {
                    if (response.getLISTEQUIPMENT().size() > 0) {
                        for (EqpInfoEntity.TestEqpEntity entity : response.getLISTEQUIPMENT()){
                            if (entity.getEQUIPMENTID().equals(s)){
                                mCarrierAdapter2.addData(s);
                                mCarrierAdapter2.notifyDataSetChanged();
                                etEqpItemWorkID.setText("");

                                etCarrier.setFocusable(true);
                                etCarrier.requestFocus();
                                etCarrier.setFocusableInTouchMode(true);
                                etCarrier.requestFocusFromTouch();
                                return;
                            }
                        }

                        showToast("当前测试机与分选机无绑定关系，请重新输入",false);
                        etEqpItemWorkID.setText("");
                    }else {
                        showToast("测试机列表为空",false);
                        etEqpItemWorkID.setText("");
                    }

                }

                @Override
                public void onFail(Throwable t) {
                    loadError(t,"EQPQUERY");
                }
            });

        });

        initEdit(etLot,s->{
            isScanmDurablelist = new ArrayList<>();
            mCarrierAdapter.setNewData(null);
            SparseArray<Boolean> checkList = mCarrierAdapter.getCheckList();
            if (mDurablelist != null && mDurablelist.size() > 0) {
                for (int i = 0; i < checkList.size(); i++) {
                    if (checkList.get(i)) {
                        checkList.put(i,false);
                    }
                }
            }
            FreeUI_EntityCallBack<BaseResponseBean<LotInfoEntity>> callBack = new CustomDialogEntityCallBack<BaseResponseBean<LotInfoEntity>>
                    (new TypeToken<BaseResponseBean<LotInfoEntity>>() {
                    }.getType(), getSupportFragmentManager(), this) {

                @Override
                public void onSuccess(Response<BaseResponseBean<LotInfoEntity>> response) {
                    super.onSuccess(response);
                    if (response.body().isSuccess(getApplicationContext(),true,getSupportFragmentManager())){
                        if(response.body().getResponse().getBody().getISPOINTCHECK().equals("Y")){
                            etProjectPcs.setVisibility(View.VISIBLE);
                            etProjectQty.setVisibility(View.VISIBLE);
                        }
                        lotInfoEntity = response.body().getResponse().getBody();
                        tvNumber.setText(lotInfoEntity.getLOT().getMAINQTY());
                        tvCircuit.setText(lotInfoEntity.getPRODUCTMODEL());
                        mDurablelist = lotInfoEntity.getDURABLELIST();
                        mLineID = lotInfoEntity.getLINEID();
                        tvLotState.setText(lotInfoEntity.getLOT().getSTATE());
                        tvLotHoldState.setText(lotInfoEntity.getLOT().getHOLDSTATE());
                        tvLotStep.setText(lotInfoEntity.getLOT().getSTEPDESC());

                        FTWorkBeginActivity.this.mCarrierAdapter.setNewData(mDurablelist);

                        if (!lotInfoEntity.getSHOWMSG().equals("")){
                            showConfirmDialog(lotInfoEntity.getSHOWMSG());
                        }
                        getMaterielInfo(s);
                    }


                }

                @Override
                public void onError(Response<BaseResponseBean<LotInfoEntity>> response) {
                    super.onError(response);
                    loadError(response.getException(),"LOTQUERY");
                }
            };

            JsonObject map = new JsonObject();
            map.addProperty("ACTIONTYPE","FTTRACKINLOTQUERY");
            map.addProperty("LOTID",s);
            map.addProperty("LOTALIAS","");
            map.addProperty("DURABLE","");
            map.addProperty("EQUIPMENTID","");
            NetUtils.requestPostNet("CPC.LOTQUERY","LOTQUERY",this,map,callBack);
        });

        mPackageCheckAdapter.setListener(new PackageCheckAdapter.onEditListener() {

            @Override
            public void onEditListener(String materielID) {
                if (getText(etLot).equals("")){
                    showToast("请先扫描批次号",false);
                    return;
                }
                FreeUI_EntityCallBack<BaseResponseBean<JsonObject>> callback = new FreeUI_DialogEntityCallBack<BaseResponseBean<JsonObject>>
                        (new TypeToken<BaseResponseBean<JsonObject>>() {
                        }.getType(), getSupportFragmentManager(), this) {

                    @Override
                    public void onSuccess(Response<BaseResponseBean<JsonObject>> response) {
                        super.onSuccess(response);
                        if (response.body().isSuccess(getApplicationContext(), false, getSupportFragmentManager())) {
                            showToast("校验成功",true);
                            isCheck = true;
//                            mPackageCheckAdapter.setNewData(null);
                        }else {
                            isCheck = false;
                        }
                    }
                    @Override
                    public void onError(Response<BaseResponseBean<JsonObject>> response) {
                        super.onError(response);
                    }
                };
                JsonObject map = new JsonObject();
                map.addProperty("ACTIONTYPE", "PACKINGPROCESS");
                map.addProperty("LOTID", getText(etLot));
//                if (mPackageCheckAdapter.getData().get(0).getVALUE().equals("")){
//                    showToast("请输入物料批次",false);
//                    return;
//                }
                //载带截取"|"符号后六位请求
                String materielId = materielID;
                if(materielId.length()>=7){
                    int startIndex = materielID.indexOf("PCB");
                    int endIndex = startIndex+6;
                    materielId = materielID.substring(startIndex,endIndex);
                }else{

                    showToast("禁止手输载带编号",false);
                    return;
                }
                map.addProperty("MATERIALBATCH", materielId);
                NetUtils.requestPostNet("CPC.PACKINGPROCESS", "TRANSFERMES",this, map, callback);
            }
        });

        initEdit(etEqpWorkID, s -> requestRunLot(s));
    }

    private void getMaterielInfo(String lotId) {
        mPackageCheckAdapter.getData().clear();
        mPackageCheckAdapter.notifyDataSetChanged();

        FreeUI_EntityCallBack<BaseResponseBean<LotInfoEntity>> callback = new FreeUI_DialogEntityCallBack<BaseResponseBean<LotInfoEntity>>
                (new TypeToken<BaseResponseBean<LotInfoEntity>>() {
                }.getType(), getSupportFragmentManager(), this) {

            @Override
            public void onSuccess(Response<BaseResponseBean<LotInfoEntity>> response) {
                super.onSuccess(response);
                if (response.body().isSuccess(getApplicationContext(), true, getSupportFragmentManager())) {
                    if (!response.body().getResponse().getBody().getMATERIALNAME().equals("")){
                        mPackageCheckAdapter.addData(response.body().getResponse().getBody());

                    }
                }
            }
            @Override
            public void onError(Response<BaseResponseBean<LotInfoEntity>> response) {
                super.onError(response);
            }
        };
        JsonObject map = new JsonObject();
        map.addProperty("ACTIONTYPE", "PACKINGPROCESS");
        map.addProperty("LOTID", lotId);
        NetUtils.requestPostNet("CPC.PACKINGPROCESS", "TRANSFERMES",this, map, callback);
    }

    /**
     * 请求正在运行的批次列表
     * @param EQPID
     */
    private void requestRunLot(String EQPID) {
        FreeUI_EntityCallBack<BaseResponseBean<LotInfoEntity>> callBack = new CustomDialogEntityCallBack<BaseResponseBean<LotInfoEntity>>
                (new TypeToken<BaseResponseBean<LotInfoEntity>>() {
                }.getType(), getSupportFragmentManager(), this) {

            @Override
            public void onSuccess(Response<BaseResponseBean<LotInfoEntity>> response) {
                super.onSuccess(response);
                if (response.body().isSuccess(getApplicationContext(),true,getSupportFragmentManager())){
                    LotInfoEntity body = response.body().getResponse().getBody();
                    if (body.getLOTLIST().size() > 0) {
                        mRunAdapter.setNewData(body.getLOTLIST());
                    }else {
//                        showToast("批次集合为空",false);
                        mRunAdapter.setNewData(null);
                    }
                }
                requestCheckByEqpId(EQPID);
            }

            @Override
            public void onError(Response<BaseResponseBean<LotInfoEntity>> response) {
                super.onError(response);
                loadError(response.getException(),"CPC.LOTQUERY");
                requestCheckByEqpId(EQPID);
            }
        };
        JsonObject map = new JsonObject();
        map.addProperty("ACTIONTYPE","LOTLISTRUNBYEQP");
        map.addProperty("EQUIPMENTID",EQPID);
        NetUtils.requestPostNet("CPC.LOTQUERY","LOTQUERY",this,map,callBack);

    }

    //eap单独增加接口
    private void requestCheckByEqpId(String EQPID) {
        FreeUI_EntityCallBack<BaseResponseBean<JSONObject>> callBack = new CustomDialogEntityCallBack<BaseResponseBean<JSONObject>>
                (new TypeToken<BaseResponseBean<JSONObject>>() {
                }.getType(), getSupportFragmentManager(), this) {

            @Override
            public void onSuccess(Response<BaseResponseBean<JSONObject>> response) {
                super.onSuccess(response);
                if (response.body().getResponse().getHeader().getRESULT().toUpperCase().equals("FAIL")) {
                    showConfirmDialog(response.body().getResponse().getHeader().getRESULTMESSAGE());
                }

            }

            @Override
            public void onError(Response<BaseResponseBean<JSONObject>> response) {
                super.onError(response);
                loadError(response.getException(),"CPC.CheckByEqpId");
            }
        };
        JsonObject map = new JsonObject();
        map.addProperty("LOTID",getText(etLot));
        map.addProperty("EQUIPMENTID",EQPID);
        NetUtils.requestPostNet("CPC.CheckByEqpId","CheckByEqpId",this,map,callBack);
    }

    private void showTips() {
        FreeApi_DialogUtils.getConfirmAndCancelDialog(this, "是", "否", "是否进行了清机台和新建批次",
                () -> {}, () -> finish()).show(getSupportFragmentManager(),"TIP_DIALOG");
    }

    @Override
    protected void initData() {

    }

    private String ListtoString(List<String> list){
        String msg = "";
        for (String s: list){
            if(msg == ""){
                msg = s;
            }else{
                msg = msg + ";" + s;
            }
        }
        return msg;
    }

    @OnClick({R.id.tvBaseSubmit,R.id.tvAdd})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tvBaseSubmit:
                if (actionControl("Submit08")) {
                    return;
                }

                boolean isLoadPack = false;

                for (String s : mDurablelist){
                    boolean isscan = false;
                    for (String sc : isScanmDurablelist){
                        if(s.equalsIgnoreCase(sc)){
                            isscan = true;
                        }
                    }
                    if(!isscan){
                        isLoadPack = true;
                        break;
                    }
                }

                if(isLoadPack){
                    showToast("当前有载具未校验", false);
                    if(mDurablelist != null && mDurablelist.size() > 0){
                        String join = ListtoString(mDurablelist);
                        FreeApi_LogUtils.saveErrorMessages("数量（" + mDurablelist.size() + "）列表:(" + join + ")","需要校验的载具：");
                    }else{
                        FreeApi_LogUtils.saveErrorMessages("列表为空！","需要校验的载具：");
                    }

                    if(isScanmDurablelist != null && isScanmDurablelist.size() > 0){
                        String join = ListtoString(isScanmDurablelist);
                        FreeApi_LogUtils.saveErrorMessages("数量（" + isScanmDurablelist.size() + "）列表:(" + join + ")","已经校验的载具：");
                    }else{
                        FreeApi_LogUtils.saveErrorMessages("列表为空！","已经校验的载具：");
                    }
                    return;
                }

                if (tvLotState.getText().toString().equals("待投产")){
                    showConfirmDialog("批次未投产，请联系计划部执行投产");
                    return;
                }

                if (tvLotState.getText().toString().equals("正在作业")){
                    showConfirmDialog("批次正在作业，请直接操作出站功能");
                    return;
                }

                if (mCarrierAdapter2.getData().size() <= 0){
                    showToast("测试机列表不能为空",false);
                    return;
                }

                if (mPackageCheckAdapter.getData().size() != 0 && !isCheck){
                    showToast("请扫描物料批次进行校验",false);
                    return;
                }
                if (mPackageCheckAdapter.getData().size() != 0 && mPackageCheckAdapter.getData().get(0).getVALUE().equals("")){
                    showToast("物料批次不能为空",false);
                    return;
                }
                String qty = getText(etQty).equals("")?"0":getText(etQty);
                FreeUI_EntityCallBack<BaseResponseBean<JsonObject>> callback = new FreeUI_DialogEntityCallBack<BaseResponseBean<JsonObject>>
                        (new TypeToken<BaseResponseBean<JsonObject>>() {
                        }.getType(), getSupportFragmentManager(), this) {

                    @Override
                    public void onSuccess(Response<BaseResponseBean<JsonObject>> response) {
                        super.onSuccess(response);
                        if (response.body().isSuccess(getApplicationContext(), false, getSupportFragmentManager())) {
                            LotUtils.lotFTTrackIn(getSupportFragmentManager(),FTWorkBeginActivity.this,getText(etEqpWorkID),getText(etLot),mCarrierAdapter.getData(),"FTTrackIn",mCarrierAdapter2.getData(),mLineID,lotInfoEntity, mPcsQtyAdapter.getData(),Double.parseDouble(qty));
                            isCheck=false;
                        }
                    }
                    @Override
                    public void onError(Response<BaseResponseBean<JsonObject>> response) {
                        super.onError(response);
                    }
                };
                JsonObject map = new JsonObject();
                map.addProperty("ACTIONTYPE", "PACKINGPROCESS");
                map.addProperty("LOTID", getText(etLot));
//                if (mPackageCheckAdapter.getData().get(0).getVALUE().equals("")){
//                    showToast("请输入物料批次",false);
//                    return;
//                }
                if (mPackageCheckAdapter.getData().size() != 0) {
                    //载带截取"|"符号后六位请求
                    String materielId = mPackageCheckAdapter.getData().get(0).getVALUE();
                    if(materielId.length()>=7){
                        int startIndex = materielId.indexOf("PCB");
                        int endIndex = startIndex+6;
                        materielId = materielId.substring(startIndex,endIndex);
                    }
                    map.addProperty("MATERIALBATCH", materielId);
                }
                NetUtils.requestPostNet("CPC.PACKINGPROCESS", "TRANSFERMES",this, map, callback);

                break;
            case R.id.tvAdd:
                if (lotInfoEntity.getCUTBASICQTY() == 0){
                    showToast("对应的切筋信息未找到或未维护数量，请联系切筋工艺维护数据",false);
                    return;
                }
                if (Integer.parseInt(getText(etPcs).equals("")?"0":getText(etPcs)) >= lotInfoEntity.getCUTBASICQTY()){
                    showToast("输入数量大于切筋数量，请重新输入",false);
                    etPcs.setText("");
                    etPcs.requestFocus();
                    return;
                }
                if (mPcsQtyAdapter.getData().size() == 5){
                    showToast("最多添加5条数据",false);
                    return;
                }
                if (getText(etPcs).equals("")){
                    showToast("尾管/盘(PCS)不能为空",false);
                    return;
                }
                mPcsQtyAdapter.addData(getText(etPcs));
                break;
        }
    }
}
